<template>
    <div class="container py-4">
        <h2 class="mb-4">端口流量统计</h2>

        <!-- 选择条件 -->
        <div class="row g-3 mb-3">
            <div class="col-md-3">
                <input v-model="port" type="number" class="form-control" placeholder="输入端口号，如 1230" />
            </div>

            <div class="col-md-3">
                <select v-model="queryType" class="form-select">
                    <option value="day">今天</option>
                    <option value="week">最近7天</option>
                    <option value="month">最近30天</option>
                </select>
            </div>

            <div class="col-md-3">
                <input v-model="queryDate" type="date" class="form-control" placeholder="选择日期" />
            </div>

            <div class="col-md-3">
                <button @click="fetchTraffic" class="btn btn-primary" :disabled="groupedDataLoading">
                    {{ groupedDataLoading ? '查询中...' : '查询' }}
                </button>
            </div>
        </div>

        <!-- 表格或加载/无数据状态 -->
        <div v-if="groupedDataLoading" class="text-muted">加载中...</div>
        <PortTrafficTable :data="parsedData" v-else-if="parsedData.length" />
        <div v-else class="text-muted">暂无数据</div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import PortTrafficTable from '../components/PortTrafficTable.vue';

import { useToast } from '../composables/useToast';
import { useApi } from '../composables/useApi';

const { success, error, warning } = useToast();

const port = ref('');
const queryType = ref('day'); // day (默认) or week or month
const queryDate = ref(''); // 查询指定日期
const parsedData = ref([]);

const filterParams = ref({
    port: '',
    type: 'day',
    date: ''
});

const {
    result: groupedData,
    fetchData: fetchGroupedData,
    loading: groupedDataLoading
} = useApi({
    url: '/terminal/flowmeter/search',
    method: 'GET',
    manual: true, // 改为手动触发
    transform: res => res.data,
    params: () => filterParams.value
});

const fetchTraffic = async () => {
    if (!port.value) return warning('请输入端口号');

    // 格式化日期为 YYYYMMDD
    let formattedDate = '';
    if (queryDate.value) {
        const dateObj = new Date(queryDate.value);
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        formattedDate = `${year}${month}${day}`;
    }

    filterParams.value = {
        port: port.value,
        type: queryType.value,
        date: formattedDate
    };

    try {
        await fetchGroupedData();
        const raw = groupedData.value;
        if (!raw) return warning('接口返回为空');

        parsedData.value = raw;
        success('查询成功');
    } catch (e) {
        console.error(e);
        error('查询失败，请检查网络或服务器错误');
    }

    console.log('Parsed Data:', parsedData.value);
};
</script>
